class Solution(object):
    def colorBorder(self, grid, row, col, color):
        m = len(grid)
        n = len(grid[0])
        used = [[0 for _ in range(n)] for _ in range(m)]
        if grid[row][col] != color:
            a_set = {(row, col)}
            now_set = {(row, col)}
            while now_set:
                x, y = now_set.pop()
                for ux, uy in [(x - 1, y), (x + 1, y), (x, y - 1), (x, y + 1)]:
                    if 0 <= ux < m and 0 <= uy < n:
                        if grid[ux][uy] == grid[row][col] and not used[ux][uy]:
                            used[ux][uy] = 1
                            a_set.add((ux, uy))
                            now_set.add((ux, uy))
            for x, y in a_set:
                flag = False
                for ux, uy in [(x - 1, y), (x + 1, y), (x, y - 1), (x, y + 1)]:
                    if 0 <= ux < m and 0 <= uy < n:
                        if (ux, uy) not in a_set:
                            flag = True
                            break
                    else:
                        flag = True
                        break
                if flag:
                    grid[x][y] = color
        return grid



data = Solution()
grid = [[1, 1], [1, 2]]
row = 0
col = 0
color = 3
print(data.colorBorder(grid, row, col, color))

